<?php

/**
 * Shall to clear app cache.
 * 
 * To clear all cache just run Console/cake cache clear
 *
 * @author jarrod
 */
class CacheShell extends AppShell {
    
    private $defaultTypes = array('models','persistent','static','views');
    public $tasks = array('ClearCache');
    
    public function clear() {
        date_default_timezone_set('Europe/Warsaw');
        $types = array();
        
        if(count($this->args) == 0){
            $types = $this->defaultTypes;
        } else {
            $types = $this->args;
        }
        
        foreach ($types as $i => &$type){
            if(strpos($type, '..') !== false){
                $this->out('<error>You must not use ".." in path</error>');
                return;
            }
            if(substr($type, 0, 1) !== '/'){
                $type = CACHE . $type;
            }
            if(!is_dir($type)){
                $this->out('<info>The directory ' . $type . ' is not exists. Skip.</info>');
                unset($types[$i]);
            }
        }
        if(empty($types)){
            $type_arg = null;
            while($type_arg == null){
                $type_arg = $this->in('Enter cache name to clear or "all".');
                if(empty($type_arg)) continue;
                if($type_arg=='all'){
                    $types = $this->defaultTypes;
                    break;
                }
                $type = CACHE . $type_arg;
                if(!is_dir($type) || strpos($type, '..') !== false){
                    $this->out('<error>The directory ' . $type . ' is invalid.</error>');
                    $type_arg = null;
                    continue;
                } else {
                    $types[] = $type;
                }
            }
        }
        
        $this->out('<info>The cache will be cleared now.</info>');
        foreach ($types as $path){
            $this->ClearCache->execute($path);
        }
        $this->out('<info>Cache cleared.</info>');
    }
}

?>
